using System.Text;
using System.Text.RegularExpressions;
using server.Services;
using server.Models;
using Microsoft.EntityFrameworkCore;

namespace server.Extensions;

public static class LibraryExtension
{
    public static IEnumerable<Book> LoadBooksFromCSV(string csv_path, BookImportOptions options, int start_id)
    {
        using (var reader = new StreamReader(csv_path, Encoding.UTF8))
        {
            var invalid_lines = new List<string>();
            var line_no = 0;
            if (options.Headless == false)
            {
                reader.ReadLine();
                line_no++;
            }
            while (reader.EndOfStream == false)
            {
                var line = reader.ReadLine();
                line_no++;
                if (line is null)
                {
                    break;
                }
                var row = line.Split(',');
                var book = new Book();
                if (options.IdColumn >= 0)
                {
                    book.ID = ParseID(row[options.IdColumn]);
                }
                if (book.ID <= 0)
                {
                    book.ID = start_id++;
                }

                book.BookName = row[options.NameColumn];
                if (string.IsNullOrEmpty(book.BookName))
                {
                    System.Console.WriteLine("Empty Book Name:" + line);
                    invalid_lines.Add($"[{line_no}]{line}");
                    continue;
                }
                book.Author = row[options.AuthorColumn];
                book.Publisher = row[options.PublisherColumn];
                book.IndexNo = row[options.IndexColumn];
                if (int.TryParse(row[options.CountColumn], out int count))
                {
                    book.TotalCount = count;
                }
                else
                {
                    System.Console.WriteLine("Invalid book count:", line);
                    invalid_lines.Add($"[{line_no}]{line}");
                    continue;
                }
                if (options.AvailableColumn >= 0 && int.TryParse(row[options.AvailableColumn], out int n))
                {
                    book.AvailableCount = n;
                }
                System.Console.WriteLine("Load Book: [{0}]{1}", book.ID, book.BookName);
                yield return book;
            }
            File.WriteAllLines("invalid.txt", invalid_lines);
        }

    }
    public async static Task ImportBooksFromCSV(this LibraryContext db, string csv_path, BookImportOptions options, int start_id)
    {
        var books = LoadBooksFromCSV(csv_path, options, start_id);
        await db.ImportBooks(books);
    }
    private static int ParseID(string id)
    {
        if (id.ToLower().StartsWith("ys") == false)
        {
            return -1;
        }
        var int_str = Regex.Match(id, @"\d+").Value;
        return String.IsNullOrEmpty(int_str) ? -1 : int.Parse(int_str);
    }

    public static void Clear<T>(this DbSet<T> table) where T : class
    {
        table.RemoveRange(table);
    }
}